/**
 * Created by artheru on 2017/1/23.
 */

function eventsInit() {
    let eventMap = {};
    let ret = {};

    ret.emit = function (content, ...path) {
        //Async post
        let pointer = eventMap;
        for (let i = 0; i < path.length; ++i) {
            let eventName = path[i];
            if (pointer[eventName])
                pointer = pointer[eventName];
            else {
                console.log("Warning: Event not emit, no such event:" + path.join("."));
                return
            }
        }

        pointer(content);
    }

    //Register an event handler.
    ret.register = function (fun, ...path) {
        let pointer = eventMap;
        for (let i = 0; i < path.length - 1; ++i) {
            let eventName = path[i];
            if (!pointer[eventName])
                pointer[eventName] = {};
            pointer = pointer[eventName];
        }
        pointer[path[path.length - 1]] = fun;
    }

    //Unregister an event handler.
    ret.unregister = function (fun, ...path) {
        let pointer = eventMap;
        for (let i = 0; i < path.length - 1; ++i) {
            eventName = path[i];
            if (pointer[eventName])
                pointer = pointer[eventName];
            else {
                console.log("Unregister Failed, no such event:" + path.join("."));
                return
            }
            pointer = pointer[eventName];
        }
        pointer[path[path.length]] = undefined;
    };

    return ret;
}

export default eventsInit();